<template>
  <div class="order-card">
    <div class="order-header">
      <div class="order-info">
        <span class="order-id">订单号: {{ order.id }}</span>
        <span class="order-status" :class="getStatusClass(order.status)">
          {{ getStatusText(order.status) }}
        </span>
      </div>
      <div class="order-date">
        {{ formatDate(order.created_at) }}
      </div>
    </div>
    
    <div class="order-body">
      <div class="order-items">
        <div 
          v-for="item in order.items" 
          :key="item.id" 
          class="order-item"
        >
          <img 
            :src="getItemImage(item)" 
            class="item-image" 
            alt="商品图片"
          />
          <div class="item-info">
            <h4 class="item-name">{{ item.product_name || '商品名称' }}</h4>
            <p class="item-price">￥{{ (item.price || 0).toLocaleString() }}</p>
          </div>
        </div>
      </div>
    </div>
    
    <div class="order-footer">
      <div class="order-total">
        总计: ￥{{ (order.total_price || 0).toLocaleString() }}
      </div>
      <div class="order-address" v-if="order.shipping_address">
        收货地址: {{ order.shipping_address }}
      </div>
      <div class="order-actions" v-if="showActions">
        <el-button 
          v-if="order.status === 'pending' || order.status === '待付款'" 
          type="primary" 
          size="small"
          @click="handlePay(order)"
        >
          立即支付
        </el-button>
        <el-button 
          v-if="order.status === 'paid' || order.status === '已付款'" 
          type="success" 
          size="small"
          @click="handleConfirm(order)"
        >
          确认收货
        </el-button>
        <el-button 
          v-if="order.status === 'pending' || order.status === '待付款'" 
          type="danger" 
          size="small"
          @click="handleCancel(order)"
        >
          取消订单
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateOrderStatus } from '@/api/order.js'

const props = defineProps({
  order: {
    type: Object,
    required: true,
    default: () => ({})
  },
  showActions: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['order-updated'])

// 订单状态处理
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消',
    // 支持中文状态值
    '待付款': '待付款',
    '已付款': '已付款',
    '已发货': '已发货',
    '已完成': '已完成',
    '已取消': '已取消'
  }
  return statusMap[status] || status
}

const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'paid': 'status-paid',
    'shipped': 'status-shipped',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled',
    // 支持中文状态值
    '待付款': 'status-pending',
    '已付款': 'status-paid',
    '已发货': 'status-shipped',
    '已完成': 'status-completed',
    '已取消': 'status-cancelled'
  }
  return classMap[status] || 'status-default'
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取商品图片
const getItemImage = (item) => {
  // 尝试从商品对象中获取图片信息
  if (item.product && item.product.images && item.product.images.length > 0) {
    // 获取第一张图片
    let imgUrl = item.product.images[0];
    
    // 如果图片是对象，获取其image属性
    if (typeof imgUrl === 'object' && imgUrl.image) {
      imgUrl = imgUrl.image;
    }
    
    // 如果是相对路径，添加基础URL
    if (typeof imgUrl === 'string' && imgUrl && !imgUrl.startsWith('http') && !imgUrl.startsWith('data:')) {
      return `http://127.0.0.1:8000${imgUrl}`;
    }
    return imgUrl;
  }
  return '/placeholder-image.jpg';
}

// 处理支付
const handlePay = async (order) => {
  try {
    ElMessageBox.confirm('确认支付该订单吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await updateOrderStatus(order.id, '已付款')
      ElMessage.success('支付成功')
      emit('order-updated')
    })
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  }
}

// 处理确认收货
const handleConfirm = async (order) => {
  try {
    ElMessageBox.confirm('确认收到商品吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await updateOrderStatus(order.id, '已完成')
      ElMessage.success('确认收货成功')
      emit('order-updated')
    })
  } catch (error) {
    console.error('确认收货失败:', error)
    ElMessage.error('确认收货失败')
  }
}

// 处理取消订单
const handleCancel = async (order) => {
  try {
    ElMessageBox.confirm('确认取消该订单吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await updateOrderStatus(order.id, '已取消')
      ElMessage.success('订单取消成功')
      emit('order-updated')
    })
  } catch (error) {
    console.error('取消订单失败:', error)
    ElMessage.error('取消订单失败')
  }
}
</script>

<style scoped>
.order-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 16px;
  background: #fff;
  transition: box-shadow 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.order-id {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.order-date {
  font-size: 12px;
  color: #999;
}

.order-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-paid {
  background: #f6ffed;
  color: #52c41a;
}

.status-shipped {
  background: #e6f7ff;
  color: #1890ff;
}

.status-completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-cancelled {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-default {
  background: #f9f9f9;
  color: #666;
}

.order-body {
  padding: 16px;
}

.order-items {
  margin-bottom: 12px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  font-size: 14px;
}

.item-price {
  color: #ff4d4f;
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.item-quantity {
  color: #999;
  font-size: 12px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  flex-wrap: wrap;
  gap: 12px;
}

.order-total {
  font-size: 16px;
  font-weight: 600;
  color: #ff4d4f;
}

.order-address {
  font-size: 14px;
  color: #666;
  flex: 1;
  min-width: 200px;
}

.order-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .order-actions {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>